package com.hkbigdata.sybx.mock;

import com.hkbigdata.sybx.bean.ElderHealthData;
import com.hkbigdata.sybx.mapper.ElderHealthDataMapper;
import org.apache.commons.lang3.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * 老年人健康数据模拟服务
 * 支持多用户并发模拟，增强错误处理
 */
@Component
@RestController
@RequestMapping("/api/elderHealthDataMock")
public class ElderHealthDataMock {
    private static final Logger logger = LoggerFactory.getLogger(ElderHealthDataMock.class);

    @Autowired
    private ElderHealthDataMapper mapper;

    @Value("${sleepMs.elderHealthMockSleep:5000}") // 默认5秒
    private Integer mockSleep;

    // 使用线程池支持多用户并发模拟
    private final ExecutorService executorService = Executors.newCachedThreadPool();

    // 跟踪每个用户的模拟任务
    private final Map<String, Future<?>> userTasks = new ConcurrentHashMap<>();

    @PostMapping("/start")
    public ResponseEntity<Map<String, Object>> startMockData(@RequestBody Map<String, String> request) {
        Map<String, Object> response = new HashMap<>();

        String userId = request.get("user_id");
        if (userId == null || userId.isEmpty()) {
            response.put("code", 400);
            response.put("message", "缺少必要参数: user_id");
            return ResponseEntity.badRequest().body(response);
        }

        // 检查该用户是否已有正在运行的任务
        if (userTasks.containsKey(userId) && !userTasks.get(userId).isDone()) {
            response.put("code", 400);
            response.put("message", "用户 " + userId + " 的模拟数据任务已经在运行");
            return ResponseEntity.badRequest().body(response);
        }

        try {
            // 为该用户启动模拟任务
            Future<?> task = executorService.submit(() -> runMockData(userId));
            userTasks.put(userId, task);

            response.put("code", 200);
            response.put("message", "用户 " + userId + " 的模拟数据已启动");
            logger.info("用户 {} 的模拟数据任务已启动", userId);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("code", 500);
            response.put("message", "启动模拟数据失败: " + e.getMessage());
            logger.error("启动用户 {} 的模拟数据任务失败", userId, e);
            return ResponseEntity.status(500).body(response);
        }
    }

    @PostMapping("/stop")
    public ResponseEntity<Map<String, Object>> stopMockData(@RequestBody Map<String, String> request) {
        Map<String, Object> response = new HashMap<>();

        String userId = request.get("user_id");
        if (userId == null || userId.isEmpty()) {
            // 如果未指定用户ID，停止所有模拟任务
            stopAllTasks();
            response.put("code", 200);
            response.put("message", "所有模拟数据任务已停止");
            return ResponseEntity.ok(response);
        }

        // 停止指定用户的模拟任务
        return stopUserTask(userId, response);
    }

//    指定userId获取信息
    @GetMapping("/{userId}")
    public ResponseEntity<Map<String, Object>> getUserHealthData(@PathVariable String userId) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 查询用户健康数据
            List<ElderHealthData> dataList = mapper.selectByUserId(userId);
            response.put("code", 200);
            response.put("data", dataList);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("code", 500);
            response.put("message", "获取用户健康数据失败: " + e.getMessage());
            logger.error("获取用户 {} 的健康数据失败", userId, e);
            return ResponseEntity.status(500).body(response);
        }
    }



    private ResponseEntity<Map<String, Object>> stopUserTask(String userId, Map<String, Object> response) {
        Future<?> task = userTasks.get(userId);
        if (task == null || task.isDone()) {
            response.put("code", 400);
            response.put("message", "用户 " + userId + " 没有正在运行的模拟数据任务");
            return ResponseEntity.badRequest().body(response);
        }

        try {
            task.cancel(true);
            userTasks.remove(userId);
            response.put("code", 200);
            response.put("message", "用户 " + userId + " 的模拟数据已停止");
            logger.info("用户 {} 的模拟数据任务已停止", userId);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("code", 500);
            response.put("message", "停止模拟数据失败: " + e.getMessage());
            logger.error("停止用户 {} 的模拟数据任务失败", userId, e);
            return ResponseEntity.status(500).body(response);
        }
    }

    private void stopAllTasks() {
        userTasks.forEach((userId, task) -> {
            if (!task.isDone()) {
                try {
                    task.cancel(true);
                    logger.info("用户 {} 的模拟数据任务已停止", userId);
                } catch (Exception e) {
                    logger.error("停止用户 {} 的模拟数据任务失败", userId, e);
                }
            }
        });
        userTasks.clear();
    }

    private void runMockData(String userId) {
        try {
            // 确保表存在
            createTableIfNotExists();

            logger.info("开始为用户 {} 生成模拟健康数据", userId);

            while (!Thread.currentThread().isInterrupted()) {
                try {
                    // 生成健康数据
                    ElderHealthData data = generateHealthData(userId);

                    // 插入数据库
                    mapper.insertData(data);

                    logger.debug("为用户 {} 插入健康数据: {}", userId, data);

                    // 休眠指定时间
                    Thread.sleep(mockSleep);
                } catch (InterruptedException e) {
                    logger.info("用户 {} 的模拟数据任务被中断", userId);
                    Thread.currentThread().interrupt();
                    break;
                } catch (Exception e) {
                    logger.error("为用户 {} 生成模拟数据时发生错误，5秒后重试: {}", userId, e.getMessage());
                    // 发生错误后等待一段时间再重试
                    Thread.sleep(5000);
                }
            }
        } catch (Exception e) {
            logger.error("用户 {} 的模拟数据任务异常终止: {}", userId, e.getMessage(), e);
        } finally {
            // 任务完成或异常终止时，从任务列表中移除
            userTasks.remove(userId);
            logger.info("用户 {} 的模拟数据任务已结束", userId);
        }
    }

    private ElderHealthData generateHealthData(String userId) {
        ElderHealthData data = new ElderHealthData();
        data.setUserId(userId);

// 生成健康数据（包含边界值检查）
//        data.setPressure(RandomUtils.nextInt(60, 140));     // 血压
        data.setSystolicPressure(RandomUtils.nextInt(90, 180));   // 收缩压
        data.setDiastolicPressure(RandomUtils.nextInt(60, 120));   // 舒张压
        // 生成血糖模拟数据并保留一位小数
        double bloodSugar = RandomUtils.nextDouble(3.9, 6.1);
        data.setBloodSugar(Math.round(bloodSugar * 10) / 10.0);     // 血糖
        // 生成血脂模拟数据并保留一位小数
        double bloodLipid = RandomUtils.nextDouble(1.7, 4.0);
        data.setBloodLipid(Math.round(bloodLipid * 10) / 10.0);     // 血脂
        data.setHeartRate(RandomUtils.nextInt(50, 130));           // 心率
        data.setRecordTime(LocalDateTime.now());                   // 记录时间

        return data;
    }

    private void createTableIfNotExists() {
        try {
            logger.debug("检查健康数据表是否存在");
            mapper.createTable();
            logger.info("健康数据表检查/创建完成");
        } catch (Exception e) {
            logger.error("创建健康数据表失败: {}", e.getMessage(), e);
            throw new RuntimeException("无法创建健康数据表", e);
        }
    }
}